﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace ProjectBase.Tools
{
    public static class Ext
    {
        #region CreateUrl
        /// <summary>
        /// Smart way how to create functional relative url.
        /// Does not matter if running on root or virtual directory.
        /// Controller without action needs different relative path then the one with action
        /// in the uri
        /// </summary>
        /// <param name="context">the object which gets this abbility</param>
        /// <param name="target">relative path from root like "/Content/Css/01Basic.css"</param>
        /// <returns>corrected url, working from any page, any controller and action</returns>
        public static string CreateUrl(this HttpContext context, string target)
        {
            if(string.IsNullOrEmpty(target))
            {
                return string.Empty;
            }
            if(context == null)
            {
                return target;
            }

            var result = new StringBuilder(context.Request.Url.AbsolutePath); // /virtaulDir/controller/action
            var relativePath = context.Request.AppRelativeCurrentExecutionFilePath.Replace("~", String.Empty); // ~/controller/action/
            result = result.Replace(relativePath, string.Empty); // /VirtualDir/
            result.Insert(0, "/");
            if (!target.StartsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                result.Append("/"); // /VirtualDir//
            }
            result.Append(target); // /VirtualDir//Target            
            result.Replace("//", "/"); // /VirtualDir/Target            
            return result.ToString();
        }
        #endregion CreateUrl
    }
}
